package cn.myzf.module.interceptor;

import cn.myzf.module.exception.ContextException;
import cn.myzf.module.util.ResponseInfo;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.internal.StringUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @package cn.myzf.module.interceptor
 * @Date Created in 2020/3/8 11:37
 * @Author myzf
 */
public class AuthInterceptor implements NettyInterceptor {

    protected static final String AUTH_COOKIE_KEY = "token";


    private static String token;

    @Override
    public void preHandle(FullHttpRequest request) {
        Map<String, String> parmMap = new HashMap<>();
            QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
            decoder.parameters().forEach((key, value) -> {
                        // entry.getValue()是一个List, 只取第一个元素
                        parmMap.put(key, value.get(0));
            });
      //  String auth = request.headers().get(HttpHeaders.Names.AUTHORIZATION);

        String token = parmMap.get("token");
        if(!StringUtil.isNullOrEmpty(token) && token.equals("myzf")){
            System.out.println("授权登录");
        }else {
            throw new ContextException(ResponseInfo.CODE_UNAUTHORIZED);
        }


        System.out.println("handle request for api  " + request.getUri());

    }

}